package com.hamilton.erik.pt.mobile.android.volley.toolbox;

import java.util.Map;

import org.json.JSONObject;

import com.android.volley.AuthFailureError;
import com.android.volley.Cache.Entry;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.HttpHeaderParser;

public class JsonObjectRequestWithParameters extends Request<JSONObject> {

	private Listener<JSONObject> listener;
	private Map<String, String> params;
	
	public JsonObjectRequestWithParameters(int method, String url, Map<String, String> params,
							Listener<JSONObject> listener, 
							ErrorListener errorListener) {
		super(method, url, errorListener);
		this.listener = listener;
		this.params = params;
	}
	
	// The JsonObjectRequest class does not have this method, but it is
	// required in order to perform the use of the form parameters.
	protected Map<String, String> getParams() throws AuthFailureError {
		return params;
	}

	@Override
	protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
		try {
			String jsonString = new String(response.data,
					HttpHeaderParser.parseCharset(response.headers));
			
			JSONObject json = new JSONObject(jsonString);
			Entry cacheHeaders = HttpHeaderParser.parseCacheHeaders(response);
			
			return Response.success(json, cacheHeaders);
		} catch (Exception e) {
			return Response.error(new ParseError(e));
		}
	}

	@Override
	protected void deliverResponse(JSONObject response) {
		listener.onResponse(response);
	}

}
